import axios from 'axios'
import { ElMessage, ElLoading } from 'element-plus'
const instance = axios.create({
  headers: {
    'Content-Type': 'application/json'
  }
})
let loading = null
instance.interceptors.request.use((config) => {
  loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  if (!window.navigator.onLine) {
    // 网络请求错误
    ElMessage.error('网络不给力，请检查网络或稍后试试')
  }
  // 请求前做什么
  return config
}, (error) => {
  // 请求错误
  loading.close()
  ElMessage.error(error.message)
})
instance.interceptors.response.use((config) => {
  loading.close()
  return config
}, (error) => {
  loading.close()
  // 请求错误
  ElMessage.error(error.message)
})

const post = (url, params) => {
  params = JSON.stringify(params)
  return new Promise((resolve, reject) => {
    instance.post(url, params)
      .then(response => {
        if (response.data.code !== 1) {
          ElMessage.error(response.data.message)
        } else {
          resolve(response.data.resObject)
        }
      })
      .catch(error => {
        reject(error)
      })
  })
}
const get = (url, params) => {
  params = JSON.stringify(params)
  return new Promise((resolve, reject) => {
    instance.get(url, {
      params: params
    })
      .then(response => {
        if (response.data.code !== 1) {
          ElMessage.error(response.data.message)
        } else {
          resolve(response.data.resObject)
        }
      })
      .catch(error => {
        reject(error)
      })
  })
}

export default {
  post,
  get
}
